from rest_framework import serializers

from category.models import Category


class CategorySerializer(serializers.ModelSerializer):
    """类别序列化器"""

    parent = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['id', 'title', 'parent']

    def get_parent(self, obj):
        if obj.parent_id != 0:
            category = Category.objects.filter(id=obj.parent_id).first()
            if category:
                return {
                    'id': category.id,
                    'title': category.title
                }
        return None
